﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint.WebControls;
using ZhukBlogLinqExamples.CONTROLTEMPLATES;
using ZhukBlogLinqExamples.Repositories;

namespace ZhukBlogLinqExamples.FieldTypes.CustomUser.Controls
{
    public class CustomUserFieldSearch : SimpleQueryControl
    {
        public Control ResultControlContainer
        {
            get { return PickerDialog.ResultControl.Parent; }
        }

        public CustomUserFieldPicker EditorControl
        {
            get { return (CustomUserFieldPicker)PickerDialog.EditorControl; }
        }

        private EmployeeFinder _finder;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            ColumnList.Visible = false;
            // Загружаем контрол
            _finder = Page.LoadControl("/_CONTROLTEMPLATES/EmployeeFinder.ascx") as EmployeeFinder;
            if (_finder != null)
            {
                // Указываем экземпляр диалога
                _finder.Dialog = PickerDialog;
                // Находим контейнер для результатов поиска
                var container = PickerDialog.ResultControl.Parent;
                // Вставляем UserControl в начало
                container.Controls.AddAt(0, _finder);
                // Оборачиваем таблицу результатов в div для разметки страницы
                container.Controls.AddAt(1, new LiteralControl(@"<div id=""DataTableContainer"">"));
                container.Controls.AddAt(3, new LiteralControl(@"</div>"));
            }
        }

        public override PickerEntity GetEntity(DataRow dataRow)
        {
            if (dataRow == null)
                return null;
            var entity = new PickerEntity
            {
                Key = Convert.ToString(dataRow["Id"]),
                DisplayText = Convert.ToString(dataRow["Title"]),
                Description = string.Empty,
                IsResolved = true
            };
            entity.EntityData.Clear();
            entity.EntityData.Add("DepartmentTitle", dataRow["DepartmentTitle"]);
            return entity;
        }

        protected override int IssueQuery(string search, string group, int pageIndex, int pageSize)
        {
            search = (search != null) ? search.Trim() : null;
            if (string.IsNullOrEmpty(search))
            {
                PickerDialog.ErrorMessage = "Нечего искать";
                return 0;
            }
            var repository = new EmployeeRepository(true);
            var employees = repository.GetEntityCollection(
                x => x.Title.Contains(search) || x.CellPhone.Contains(search))
                .ToList();
            if (employees.Count == 0)
            {
                PickerDialog.ErrorMessage = "Ничего не найдено";
                return 0;
            }
            // Создаем таблицу и наполняем её
            var table = CreateDataTable();
            foreach (var employee in employees)
            {
                var row = table.NewRow();
                row["Id"] = employee.Id;
                row["Title"] = employee.Title;
                row["DepartmentTitle"] = employee.DepartmentTitle;
                table.Rows.Add(row);
            }
            PickerDialog.Results = table;
            PickerDialog.ResultControl.PageSize = table.Rows.Count;
            // Указываем параметры столбцов таблицы
            var rc = PickerDialog.ResultControl as TableResultControl;
            if (rc != null)
            {
                rc.ColumnNames.AddRange(new[] { "Id", "Title", "DepartmentTitle" });
                rc.ColumnDisplayNames.AddRange(new[] { "ИД", "ФИО", "Отдел", });
                rc.ColumnWidths.AddRange(new[] { "15%", "50%", "35%" });
            }
            // Возвращаем кол-во найденных элементов
            return table.Rows.Count;
        }

        public static DataTable CreateDataTable()
        {
            DataColumn column;
            var table = new DataTable { Locale = CultureInfo.InvariantCulture };
            foreach (string columnName in new[] { "Title", "DepartmentTitle", "CellPhone" })
            {
                column = new DataColumn { DataType = typeof(string), ColumnName = columnName };
                table.Columns.Add(column);
            }
            var hiddenColumnNames = new[] { "Id" };
            foreach (var columnName in hiddenColumnNames)
            {
                column = new DataColumn
                {
                    DataType = typeof(string),
                    ColumnName = columnName
                };
                table.Columns.Add(column);
            }
            return table;
        }
    }


}
